package com.job51.hro.datacheckservice.util;

import com.job51.hro.datacheckservice.service.ErrorMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.function.Function3;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author pengfei.ma
 * @since 1.0.0
 */
public class FileUtil {

    static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    public static String readTextWithPattern(String filePath, String startPattern, int[]  startPatternGroupNum, String endPattern, int[]  endPatternGroupNum) throws Exception {
        return  FileUtil.readTextWithPattern(filePath,startPattern,startPatternGroupNum,null,endPattern,endPatternGroupNum,null);
    }


    /**
     * 按照正则读取文件内容，从开始读到结束前一行
     * @param filePath  文件路径
     * @param startPattern 匹配开始正则
     * @param startPatternGroupNum  数组代表group中某一项匹配则算成功
     * @param startOtherRules 其他闭包函数规则
     * @param endPattern 匹配结束开始正则
     * @param endPatternGroupNum 数组代表group中某一项匹配则算成功
     * @param endOtherRules  其他闭包函数规则  -n 表示无条件向后追加n行内容,0表示停止追加，1表示继续追加
     */
    public static String readTextWithPattern(String filePath, String startPattern, int[] startPatternGroupNum, Function<String,Boolean> startOtherRules, String endPattern, int[] endPatternGroupNum, Function3<String,StringBuilder,Object,Integer> endOtherRules) throws Exception {
           File file = new File(filePath);
           StringBuilder text= new StringBuilder();
           if (file.isFile() && file.exists()) {
               InputStreamReader read = new InputStreamReader(
                       new FileInputStream(file), StandardCharsets.UTF_8);
               BufferedReader bufferedReader = new BufferedReader(read);
               String lineTxt ;
               Pattern pStart = Pattern.compile(startPattern);
               Pattern pEnd = Pattern.compile(endPattern);
               boolean append= false;
               //读取一行
               while ((lineTxt = bufferedReader.readLine()) != null) {
                   Matcher startMatcher = pStart.matcher(lineTxt);
                   if (startMatcher.find() && startOtherRules != null) {
                       String matchInfo;
                       for (int j : startPatternGroupNum) {
                           matchInfo = startMatcher.group(j);
                           if (startOtherRules.apply(matchInfo)) {
                               append = true;
                               break;
                           }
                       }
                   }
                   if (append) {
                       Matcher endMatcher = pEnd.matcher(lineTxt);
                       if (endMatcher.find() && endOtherRules != null) {
                           String matchInfo;
                           Integer res;
                           for (int j : endPatternGroupNum) {
                               matchInfo = endMatcher.group(j);
                               res = endOtherRules.apply(matchInfo, text, null);
                               if ( res==0) {
                                   append = false;
                                   break;
                               }else if(res < 0){
                                  while(res<0){
                                      text.append(lineTxt).append("\r\n");
                                      res++;
                                      if(res<0) {
                                          lineTxt = bufferedReader.readLine();
                                      }
                                  }
                                  text.append("\r\n");
                                  append=false;
                               }
                           }
                       }
                       if (append) {
                           text.append(lineTxt).append("\r\n");
                       }
                   }
               }
               read.close();
           } else {
               throw new RuntimeException("找不到指定文件");
           }
           return text.toString();
    }

    /**
     * 按一定约定处理字符串
     */
    public static String specialSignReplace(String str){
        String tempStr = str;
        String pattern = "\\{([^}]+)}";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(str);
        String dateFormat;
        int matcher_start= 0;
        while (matcher.find(matcher_start)) {
            dateFormat = matcher.group(1);
            String replaceDate = DateUtil.getString(dateFormat);
            tempStr=tempStr.replace("{"+dateFormat+"}",replaceDate);
            matcher_start=matcher.end();
        }
        return  tempStr;
    }

    public static  void createAndWriteContent(String filePath,String fileName,String content){
        FileWriter fw ;
        try
        {
            File filep= new File(filePath);
            if (!filep.exists())
            {
                filep.mkdirs();
            }
            File file = new File(filePath+"/"+fileName);
            if (!file.exists())
            {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            BufferedWriter bw=new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            log.error("写文件出错"+e.getMessage(),e);
        }
    }


    /**
     * 递归方式删除指定文件夹内全部文件和文件夹
     *
     * @param path 文件路径
     */
    public static void delFileAndDir(String path) {
        File file = new File(path);
        //判断指定路径的文件或文件是否存在
        if (file.exists() && file.isDirectory()) {
            //返回当前路径下的所有文件和文件夹名称
            File[] files = file.listFiles();
            //遍历所有文件及文件夹
            for (File f : files) {
                //如果是文件就删除
                if (f.isFile()) {
                    //删除文件
                    f.delete();
                } else {
                    //如果是目录，则调用递归方法
                    delFileAndDir(f);
                }
                //删除空目录
                f.delete();
            }
            file.delete();
        }
    }


    /**
     * 递归方式删除指定文件夹内全部文件和文件夹
     *
     * @param file 文件
     */
    public static void delFileAndDir(File file) {
        //判断指定路径的文件或文件是否存在
        if (file.exists() && file.isDirectory()) {
            //返回当前路径下的所有文件和文件夹名称
            File[] files = file.listFiles();
            //遍历所有文件及文件夹
            for (File f : files) {
                //如果是文件就删除
                if (f.isFile()) {
                    //删除文件
                    f.delete();
                } else {
                    //如果是目录，则调用递归方法
                    delFileAndDir(f);
                }
                //删除空目录
                f.delete();
            }
        }
    }

    public static String getFileNameNoExt(String path) {
        int startIndex = path.lastIndexOf("/") + 1;
        int endIndex = path.lastIndexOf(".");
        return path.substring(startIndex, endIndex);
    }


    public static String getFileName(String path) {
        int index = path.lastIndexOf("/");
        if(index == -1){
            index = path.lastIndexOf("\\");
        }
        return path.substring(index + 1);
    }

}
